package com.woniuxy.yoga.user.service.mq;

import com.woniuxy.yoga.commons.redis.util.RedisUtil;
import com.woniuxy.yoga.commons.redis.util.rediskeyutil.UserRedisKeyUtil;
import com.woniuxy.yoga.commons.sms.util.SMSUtil;
import org.springframework.amqp.rabbit.annotation.Queue;
import org.springframework.amqp.rabbit.annotation.RabbitHandler;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.util.Map;

@Component
public class SendUserRegisterCodeConsumer {

    @Resource
    private RedisUtil redisUtil;

    @Resource
    private SMSUtil smsUtil;

    @RabbitListener(queuesToDeclare = {
            @Queue(name = "userRegister.sendCode")
    })
    @RabbitHandler
    public void consume(Map<String,Object> message) throws Exception {
        String phone = (String) message.get("phone");
        //调用短信api
        String code = smsUtil.send(phone);
        //将验证码保存到redis中，过期时间为5分钟
        redisUtil.set(UserRedisKeyUtil.userRegisterCodeKey(phone),code,5*60);
        //每发送一次短信，在redis中保存一个key 过期时间一分钟 当该key存在时不允许再次发送
        redisUtil.set(UserRedisKeyUtil.userRegisterCodeOneMinute(phone),code,60);
        //每发送一条短信，使redis中的一个key的值自增1
        if (redisUtil.hasKey(UserRedisKeyUtil.userSendNumbers(phone))){
            redisUtil.incr(UserRedisKeyUtil.userSendNumbers(phone));
        }else{
            redisUtil.set(UserRedisKeyUtil.userSendNumbers(phone),"1",60*60);
        }
    }
}
